Tag: asp.net web api

具有路由属性的不明确控制器名称:具有相同名称和不同命名空间的控制器,用于版本控制

我正在尝试添加API版本,我的计划是为不同命名空间中的每个版本创建一个控制器。 我的项目结构如下所示(注意:每个版本没有单独的区域) Controllers | |—Version0 | | | |—– ProjectController.cs | |—– HomeController.cs | |—Version1 | |—– ProjectController.cs |—– HomeController.cs 我正在使用RoutingAttribute作为路由。 因此,Version0中的ProjectController具有路由function namespace MyProject.Controllers.Version0 { class ProjectController : BaseController { … [Route(api/users/project/getProjects/{projectId})] public async GetProjects(string projectId) { … } } } Version1中的ProjectController和具有route的函数 namespace MyProject.Controllers.Version1 { class ProjectController : BaseController { … [Route(api/v1/users/project/getProjects/{projectId})] public async GetProjects(string […]

自定义授权属性在WebAPI中不起作用

public class CustomAuthorizeAttribute : AuthorizationFilterAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { return true;// if my current user is authorised } } 上面是我的CustomAuthorizeAttribute类和 [CustomAuthorize] // both [CustomAuthorize] and [CustomAuthorizeAttribute ] I tried public class ProfileController : ApiController { //My Code.. } 当我打电话的时候 http://localhost:1142/api/Profile 它没有触发CustomAuthorizeAttribute 我的FilterConfig类的内容如下所示 public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { […]

为什么Web API不会反序列化,但JSON.Net会?

Web API如何无法反序列化JSON.Net反序列化的对象? 这是Web API控制器: public void Put(EditorSubmissionMainView ajaxSubmission) { // ajaxSubmission: EditorSubmissionMainView with all values (‘data’ also == null) string json = “{\”id\”:\”row_1377\”,\”data\”:{\”ROTATION\”:\”1\”,\”EQUIPMENT\”:[{\”id\”:\”6\”},{\”id\”:\”8\”}],\”NOTES\”:\”\”}}”; EditorSubmissionMainView foo = Newtonsoft.Json.JsonConvert.DeserializeObject(json) as EditorSubmissionMainView; // foo is a EditorSubmissionMainView but properly deserialized. } 这是由Fiddler捕获并格式化的JSON: { “id”: “row_1377”, “data”: { “ROTATION”: “1”, “EQUIPMENT”: [{ “id”: “6” }, { “id”: “8” }], […]

如何从WebApi动作返回html页面?

我正在寻找一个WebApi示例,其中默认路由将给定调用者返回给定的html页面。 我的路线和行动设置如下。 我只想向他发送index.html页面,而不是重定向,因为他在正确的位置。 http://localhost/Site // load index.html // WebApiConfig.cs config.Routes.MapHttpRoute( name: “Root”, routeTemplate: “”, defaults: new { controller = “Request”, action = “Index” } ); // RequestControlller.cs [HttpGet] [ActionName(“Index”)] public HttpResponseMessage Index() { return Request.CreateResponse(HttpStatusCode.OK, “serve up index.html”); } 如果我使用这个错误,那么更好的方法是什么,你能指点我一个例子吗? WebApi 2与.NET 4.52 编辑:嗯,改进了它,但得到了json头而不是页面内容。 public HttpResponseMessage Index() { var path = HttpContext.Current.Server.MapPath(“~/index.html”); var content = […]

Web表单中的ASP.NET Web Api

我正在尝试使用Visual Studio 2010(sp1)在WEB FORMS中使用asp.net web api我已经完成了这个步骤http://myrandomykien.blogspot.com/2012/02/simplest-web-api-site-with -nuget.html 当我使用visual studio开发服务器时它可以工作 ,但是当我使用iis 7.5时,我得到一个错误HTTP 404.0 – 未找到。 编辑 这是我的Global-asax protected void Application_Start(object sender, EventArgs e) { RouteTable.Routes.MapHttpRoute( name: “DefaultApi”, routeTemplate: “api/{controller}/{id}”, defaults: new { id = System.Web.Http.RouteParameter.Optional } ); } 这是api类 public class GreetingController : ApiController { public string GetGreeting(string id) { return String.Format(“Hello {0}”, id); } }

来自ASP.Net Web API 2的统一,一致的错误响应

我正在开发一个Web API 2应用程序,我正在尝试以统一的方式格式化错误重定位(这样消费者也将知道他们可以检查哪些数据对象/结构以获得有关错误的更多信息)。 这是我到目前为止所得到的: { “Errors”: [ { “ErrorType”:5003, “Message”:”Error summary here”, “DeveloperAction”:”Some more detail for API consumers (in some cases)”, “HelpUrl”:”link to the docs etc.” } ] } 这适用于应用程序本身抛出的exception(即内部控制器)。 但是,如果用户请求错误的URI(并获得404)或使用错误的动词(并获得405)等,Web Api 2会发出默认错误消息,例如 { Message: “No HTTP resource was found that matches the request URI ‘http://localhost/abc’.” } 有没有办法捕获这些类型的错误(404,405等)并将它们格式化为上面第一个例子中的错误响应? 到目前为止,我已经尝试过: 自定义ExceptionAttribute inherting ExceptionFilterAttribute 自定义ControllerActionInvoker加入ApiControllerActionInvoker IExceptionHandler (Web […]

System.Net.Http.HttpRequestException将内容复制到流时出错

我在.Net 4.5.2框架中使用HttpClient类。 我正在对第三方Web服务进行PostAsync。 这篇文章有80%的时间有效,20%的时间我们的回复被缩短了。 在这种情况下,我们得到以下exception: System.Net.Http.HttpRequestException: 将内容复制到流时出错。 —> System.IO.IOException:无法从传输连接读取数据:远程主机强制关闭现有连接。 —> System.Net.Sockets.SocketException:远程主机在System.Net.Sockets.NetworkStream.BeginRead(Byte []缓冲区,Int32偏移量,Int32大小,AsyncCallback回调,对象状态)强制关闭现有连接—内部exception堆栈跟踪的结束—在System.Net.FixedSizeReader.StartReading()的System.Net.Sockets.NetworkStream.BeginRead(Byte []缓冲区,Int32偏移量,Int32大小,AsyncCallback回调,对象状态)在System.Net.Security._SslStream.StartFrameHeader(Byte []缓冲区,Int32偏移量,Int32计数,AsyncProtocolRequest asyncRequest)处于System.Net.Security._SslStream.StartReading(Byte []缓冲区,Int32偏移量,Int32计数,AsyncProtocolRequest asyncRequest)在System.Net.Security.PlsStream.BrocessRead(Byte []缓冲区,Int32偏移量,Int32计数,AsyncProtocolRequest asyncRequest)处于System.Net.TlsStream.BeginRead(Byte []缓冲区,Int32偏移量,Int32大小,AsyncCallback asyncCallback,Object asyncState) )在System.Net.ConnectStream.BeginReadWithoutValidation(Byte []) System.Net.Http.HttpClientHandler.WebExceptionWrapperStream上的System.Net.ConnectStream.BeginRead(Byte []缓冲区,Int32偏移量,Int32大小,AsyncCallback回调,对象状态)处的缓冲区,Int32偏移量,Int32大小,AsyncCallback回调,对象状态) System.Net.Http.StreamToStreamCopy.StartRead()的.BeginRead(Byte []缓冲区,Int32偏移量,Int32计数,AsyncCallback回调,对象状态) 随后的相同请求成功。 这不是我们可以重新设置的请求,因为已经放置了业务。 所以它让我们陷入了尴尬境地。 这是我的代码: using (var httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Authorization = authorizationHeader; HttpContent httpContent = new StringContent(someXml); //Exception occurs on next line… var response = […]

Web API自定义validation,以根据已批准值列表检查字符串

我想validationWeb API REST命令的输入。 我希望它可以像下面的State一样使用限制参数有效值的属性进行修饰。 public class Item { … // I want State to only be one of “New”, “Used”, or “Unknown” [Required] [ValidValues({“New”, “Used”, “Unknown”})] public string State { get; set; } [Required] public string Description { get; set; } … } 有没有办法在不违背Web API的情况下做到这一点。 理想情况下,该方法类似于Ruby on Rails的自定义validation 。

ASP.Net WebApi:如何在运行时加载其他控制器

在我的Asp.Net MVC 4 WebApi应用程序中,我希望稍后(在WebApi初始化之后)动态加载其他WebApiControllers,它们位于不同的程序集中。 此外,我想在运行时为这些控制器添加路由。 我很奇怪,如果可以的话。 我的目标是构建一个Web应用程序,我可以在其中上传控制器(已编译的程序集),控制器将自动托管在此应用程序中。 我已经尝试通过实现我自己的AssemblyResolver类来实现它,但是(据我所见),AssemblyResolver在初始化阶段加载一次。 可能有一个“重新加载”所有控制器的选项。 任何帮助将不胜感激! 马吕斯

使用ASPNET MVC 4和webapi自定义httphandler和routehandler

我正在研究ASPNET MVC 4和WebApi。 webapi方法将由移动设备使用。 我们需要保护服务,我们正在使用的是以某种特定方式加密数据。 现在,我需要在到达控制器之前解密呼叫。 如果解密的信息有效,它应该照常继续到控制器,如果没有,我将路由用户一些错误方法。 为了实现这一点,我认为最好的选择是自定义HttpHandler和自定义RouteHandler。 我在这里按照教程 public class MvcSecurityRouteHandler:IRouteHandler { public System.Web.IHttpHandler GetHttpHandler(RequestContext requestContext) { return new MvcSecurityHttpHandler(requestContext); } } public class MvcSecurityHttpHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState, IRouteHandler { public RequestContext RequestContext { get; set; } public MvcSecurityHttpHandler(RequestContext requestContext) { this.RequestContext = requestContext; } public bool IsReusable { get { return true; } […]