Tag: asp.net web api2

无法在web api控制器中遇到断点

当我尝试调试此代码时: // POST: api/Events [HttpPost] public async Task PostEvent([FromBody] object savedEvent) { Event addedEvent = JsonConvert.DeserializeObject(savedEvent.ToString()); if (!ModelState.IsValid) { return BadRequest(ModelState); } 无法达到这条线: Event addedEvent = JsonConvert.DeserializeObject(savedEvent.ToString()); Debuger反应就像我点击继续但代码过去没有执行。 我真的很困惑。 谢谢你的帮助。

C#Web API POST参数FromBody始终为null

我已经在网上搜了好几个小时,并尝试了StackOverflow上描述的许多不同的解决方案。 我之前已经问过类似的问题,但没有一个答案或评论对我有用。 问题:我有一个.NET Web API,它有一个带有一些参数的Post方法。 其中一个参数是一个复杂的对象,应该从正文中读取(即JSON)。 但是,此对象始终为null 。 这是我的代码: // POST api/worksheets/post_event/true/false [Route(“post_event/{newWorksheet}/{eindEvent}”)] [HttpPost] public Event Post(bool newWorksheet, bool eindEvent, [FromBody] Event eventData) { return eventData; } 要明确:eventData是始终为null的对象。 布尔值被正确读取。 完整的请求正文是: POST http://localhost:5000/api/worksheets/post_event/true/false Content-Type: application/json {“Persnr”:1011875, “WorksheetId”:null, “Projectnr”:81445, “Uursoort”:8678, “Tijd”:{“09-08-2016 9:25”}} 作为参考,这是Event-class: public class Event { public long Persnr { get; set; } public int WorksheetId […]

WebAPI 2属性路由,区域不起作用

我无法使WEBAPI 2属性路由工作。 我正在寻找的路由方案是/api/{product}/{controller}/{id-optional} ,所以就像/api/Vision/IdCard 。 控制器位于一个区域中,并设置如下: namespace DataServices.Controllers.Vision { [RoutePrefix(“api/vision”)] public class IdCardController : BaseApiController { [System.Web.Mvc.RequireHttps] [Route(“idcard”)] public IdCardViewModel Get(HttpRequestMessage request) {…} 每当我做到这一点,我得到一个404 。 我包含了命名空间,因为该区域位于其自己的命名空间中。 WEBAPI属性路由中是否支持区域? 编辑:WebApiConfig看起来像这样: config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: “DefaultApi”, routeTemplate: “api/{controller}/{id}”, defaults: new { id = RouteParameter.Optional } );

需要我的web api 2控制器的路由

我有一个简单的WebApi2控制器,它返回XML,但我无法使用我定义的路由正确添加另一个方法: namespace CBMI.WebAPIservice.Controllers { public class MarkersController : ApiController { public HttpResponseMessage Get(int? id) { int i = id.HasValue ? id.Value : 0; XmlDocument docContent = GetXmlDataFromDB(i); return new HttpResponseMessage { Content = new StringContent(docContent.InnerXml.ToString(), Encoding.UTF8, “application/xml”) }; } public HttpResponseMessage GetGrantsIS() { XmlDocument docContent = GetXmlDataFromDB(); return new HttpResponseMessage { Content = new StringContent(docContent.InnerXml.ToString(), […]

重用WEB API OData控制器的现有ASP.NET-MVC 5 Identity 2授权,以便轻松登录其他应用程序?

我有完整的ASP.NET-MVC5应用程序,我通过WEB API 2 OData控制器进行了扩展。 比如我有: public class PersonController : ODataController 和需要授权的MVC控制器 [Authorize] public class PersonController : Controller 两个控制器都在我的DbSets中使用ApplicationDbContext 我不想通过WEB API控制器向世界上的每个人提供有关人员的数据。 我已经在我的MVC应用程序中拥有User , Moderator和Admin角色。 我可以以某种方式使用已经存在的授权模块(Identity 2.x),当有人试图从Person WEB API Controller获取数据时要求登录。 例如: http://localhost:17697/odata/Person?$expand=ReceivedCalls 直接问题 : 如果我做: [Authorize] public class PersonController : ODataController { 然后当我去链接时: http://localhost:17697/odata/Person 我被重定向到登录页面。 但是这个登录页面适用于人类。 如何使客户端应用程序轻松登录。

ApiController扩展方法 – 无法访问ResponseMessage

我想为ApiController创建扩展方法,以便能够返回自定义内容。 我的想法是用我自己的细节返回自定义错误。 我想返回类似于OAuthAuthorizationServerProvider返回的错误的自定义错误: { “error”: “invalid_grant”, “error_description”: “You have 3 more attempts before Your account will be locked.” } 在我的ApiController里面我添加了这个方法: public IHttpActionResult Test() { HttpError err = new HttpError(); err[“error”] = “40001”; err[“error_description”] = “Something is wrong”; var response = Request.CreateErrorResponse(HttpStatusCode.NotFound, err); return ResponseMessage(response); } 这让我看起来很好看: { “error”: “40001”, “error_description”: “Somethis is wrong” } 我尝试将此转换为以下扩展方法: […]

WebAPI 2.0 Post未反序列化List 属性

我已经回顾了我在这里可以找到的所有类似的文章,并尝试了任何看起来可能没有成功的事情(因为我现在正在问这个问题)。 我有一个带有POST操作的webAPI 2.0控制器,它接受一个类型为Reservation的对象。 除其他外,该对象包含名为Items的属性,该属性属于EquipmentItems类型。 可以想象,这是一个List属性。 我发送预订对象(使用PostAsJsonAsync(“api/Reservation”, reservation).Result如果它对任何人PostAsJsonAsync(“api/Reservation”, reservation).Result重要)。 当我进入API控制器时, Reservation对象完全填充了除EquipmentItems属性之外的所有内容。 本着完全公开的精神, Reservation类中的Items属性实际上被定义为List,其中T是IItemData接口。 EquimpentIteminheritance自IItemData ,因此不确定这是否会使问题复杂化。 本机控制器反序列化器可以不处理T是接口的List吗? 我所知道的是将List定义为常规数组。 这非常有效,但我有其他要求导致我使用List。 有关如何正确反序列化List属性的任何建议?

返回HttpResponseMessage并配置Application Insights时,WebAPI响应永远不会完成

我有一个MVC5 / WebAPI2应用程序,自我创建Web项目以来已启用Application Insights。 WebApi返回对象的方法(例如字符串,模型对象)按预期返回 – 序列化为JSON或XML。 public class TestController : ApiController { [HttpGet] [AllowAnonymous] async public Task ReadString(int id) { HttpResponseMessage response = Request.CreateResponse(); string str; using (HttpClient client = new HttpClient()) { Uri uri = new Uri(“http://someurl.com/resource.rss”); str = await client.GetStringAsync(uri); } response.Content = new StringContent(str); response.Content.Headers.ContentLength = str.Length; return response; } } […]

如何在webapi上传中获取Multipart文件的流?

我需要使用Stream(Azure Blobstorage)上传文件,并且无法找到如何从对象本身获取流。 见下面的代码。 我是WebAPI的新手,并使用了一些示例。 我正在获取文件和filedata,但我的方法上传它并不正确。 因此,我需要将其转换或转换为普通Stream,此刻看起来有点难:) 我知道我需要使用ReadAsStreamAsync().Result以某种方式,但它在foreach循环中崩溃,因为我得到两个provider.Contents(第一个似乎正确,第二个没有)。 [System.Web.Http.HttpPost] public async Task Upload() { if (!Request.Content.IsMimeMultipartContent()) { this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType); } var provider = GetMultipartProvider(); var result = await Request.Content.ReadAsMultipartAsync(provider); // On upload, files are given a generic name like “BodyPart_26d6abe1-3ae1-416a-9429-b35f15e6e5d5” // so this is how you can get the original file name var originalFileName = GetDeserializedFileName(result.FileData.First()); // […]

中间件中的HttpContext .NET核心保存实例

将HttpContext实例存储在中间件中是否安全? 例: public class TestMiddleware { private readonly RequestDelegate next; private HttpContext context; public TestMiddleware(RequestDelegate next) { this.next = next; } public async Task Invoke(HttpContext context) { try { this.context = context; 我想在其他私有方法中使用它来处理它,所以我可以将它作为参数传递给那些函数或使用它,如示例中所示。 但它是否安全?