Tag: asp.net web api

每种类型自定义Json.NET序列化程序设置

我正在使用ApiController,它使用全局HttpConfiguration类来指定JsonFormatter设置。 我可以非常容易地全局设置序列化设置: config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects; 问题是并非所有设置都适用于我的项目中的所有类型。 我想为执行多态序列化的特定类型指定自定义TypeNameHandling和Binder选项。 如何在per-type上指定JsonFormatter.SerializationSettings,或者至少在per-ApiController上指定?

如何将HttpRequestMessage转发到另一台服务器

将http web api请求转发到另一台服务器的最佳方法是什么? 这是我正在尝试的: 我有一个.NET项目,当我得到某些API请求时,我想修改请求,将其转发到另一台服务器,并返回第二台服务器发送的响应。 我正在做以下事情: [Route(“forward/{*api}”)] public HttpResponseMessage GetRequest(HttpRequestMessage request) { string redirectUri = “http://productsapi.azurewebsites.net/api/products/2”; HttpRequestMessage forwardRequest = request.Clone(redirectUri); HttpClient client = new HttpClient(); Task response = client.SendAsync(forwardRequest); Task.WaitAll(new Task[] { response } ); HttpResponseMessage result = response.Result; return result; } 克隆方法定义为: public static HttpRequestMessage Clone(this HttpRequestMessage req, string newUri) { HttpRequestMessage clone = […]

Web Api 2.2 OData V4function路由

我有一个使用OData v4的Web Api 2.2项目。 正常的EntitySet配置可以根据需要使用所有http谓词。 我遇到问题的地方是尝试公开自定义函数。 我开始尝试做一些与标准示例不同的事情,但我一直支持尝试使基本示例函数正常工作。 这是我的启动配置(直接来自MS示例): using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; using System.Web.OData.Builder; using System.Web.OData.Extensions; namespace Test.Service { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // other entitysets that don’t have functions builder.EntitySet(“Products”); builder.Namespace = “ProductService”; builder.EntityType().Collection .Function(“MostExpensive”) .Returns(); config.MapODataServiceRoute( “odataroute” , “odata” , builder.GetEdmModel() ); […]

使用WebApi和映射模型实现OData

我正在尝试在WebApi中实现OData。 我正在使用存储库模式和EF5(在后端),这仍然与我找到的所有示例一致。 这是事情变得不稳定的地方。 我试图隐藏EF生成的类隐藏在控制器中使用AutoMapper映射的模型后面。 我看到的例子似乎都归还了回购中的任何内容 我不想在控制器中但在存储库中应用OData参数(已映射的结果)以保留延迟执行的值。 我可以将ODataCriteria传递到存储库中,但是当我尝试Appy时,我得到一个错误,因为看起来选项/结果是从表示层而不是IQueryable 键入IQueryable 。 我在另一篇文章中看到其他人没有注意到这一点,但是,它只是该post的一小部分,似乎没有帮助。 还有其他人处理过这件事吗? 我真的不想暴露EF类。 哦,我先使用DB。 提前致谢…

asp.net核心中的TempData null

我试图在asp.net核心中使用TempData但是我在TempData的get方法上得到一个null值。 任何人都可以告诉我如何在asp.net核心中使用TempData 以下是我根据研究添加的内容。 Project.json文件 { “dependencies”: { “Microsoft.NETCore.App”: { “version”: “1.0.1”, “type”: “platform” }, “Microsoft.AspNetCore.Mvc”: “1.0.1”, “Microsoft.AspNetCore.Routing”: “1.0.1”, “Microsoft.AspNetCore.Server.IISIntegration”: “1.0.0”, “Microsoft.AspNetCore.Server.Kestrel”: “1.0.1”, “Microsoft.Extensions.Configuration.EnvironmentVariables”: “1.0.0”, “Microsoft.Extensions.Configuration.FileExtensions”: “1.0.0”, “Microsoft.Extensions.Configuration.Json”: “1.0.0”, “Microsoft.Extensions.Logging”: “1.1.0”, “Microsoft.Extensions.Logging.Console”: “1.0.0”, “Microsoft.Extensions.Logging.Debug”: “1.0.0”, “Microsoft.Extensions.Options.ConfigurationExtensions”: “1.0.0”, “Microsoft.EntityFrameworkCore.SqlServer”: “1.1.0”, “Microsoft.EntityFrameworkCore.Tools”: “1.1.0-preview4-final”, “Microsoft.EntityFrameworkCore.Design”: “1.1.0”, “Microsoft.EntityFrameworkCore.SqlServer.Design”: “1.1.0”, “DataBase”: “1.0.0-*”, “UnitOfWork”: “1.0.0-*”, “ViewModel”: “1.0.0-*”, “Common”: “1.0.0-*”, “System.IdentityModel.Tokens.Jwt”: “5.0.0”, “Microsoft.AspNetCore.Authentication.JwtBearer”: […]

返回JSON对象(ASP.NET WebAPI)

我有ASP.NET Web API 它返回我这样的JSON [{“CompanyID”:1,”CompanyName”:”Тест”},{“CompanyID”:5,”CompanyName”:”Фокстрот”}] 据我所知,这是Json数组,但我需要返回JSOn对象而不是它 像这样: {“results”:[{“CompanyID”:1,”CompanyName”:”Тест”},{“CompanyID”:5,”CompanyName”:”Фокстрот”}]} 这是我的GetCompanies控制器: public class GetCompaniesController : ApiController { private ApplicationDbContext db = new ApplicationDbContext(); // GET: api/GetCompanies public IQueryable GetCompanies() { return db.Companies; } // GET: api/GetCompanies/5 [ResponseType(typeof(Companies))] public async Task GetCompanies(int id) { Companies companies = await db.Companies.FindAsync(id); if (companies == null) { return NotFound(); } return […]

DelegatingHandler不执行ASP.Net Web Api

今天我在Web Api应用程序中遇到了一个奇怪的行为 protected void Application_Start() { FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); GlobalConfiguration.Configuration .MessageHandlers.Add(new DummyMessageHandler()); } 我的DelegatingHandler看起来像这样。 public class DummyMessageHandler : DelegatingHandler { protected override Task SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { * if (request.Headers.Authorization.Scheme == “Basic”) Thread.CurrentPrincipal = new GenericPrincipal( new GenericIdentity(“Authenticated”), new string[0]); return base.SendAsync(request, cancellationToken); } } 我遇到的问题是委托处理程序没有被执行。 我在标有*的行中有一个断点,我的代码执行从未停止过。 我的nuget packages.config如下: 我在看这个很长一段时间了,你能指点我错过的东西吗? 谢谢

带有电子邮件地址参数的WebApi方法从HttpClient返回404

我有一个WebApi控制器,其方法如下: [HttpGet] [AcceptVerbs(“GET”)] public HttpResponseMessage Run(string reportName, int someId, string someText, DateTime asOfDate, string username) 我有专门为此操作配置的自定义路由。 当我将浏览器导航到Web服务时,一切正常,并执行相应的操作: http://localhost:xxxx/ControllerName/Run/asdf/1/asdf/07-01-2012/user@domain.com 但是,当我尝试使用HttpClient以编程方式调用Web服务并执行“获取”时,我收到404错误。 当username参数不是电子邮件地址时,我不会收到错误。 例如,当用户名只是“用户”时,一切正常。 以下是示例代码: var url = “http://localhost:xxxx/ControllerName/Run/asdf/1/asdf/07-01-2012/user@domain.com” var client = new System.Net.Http.HttpClient(); var response = client.Get(url); //fails here with 404 error response.EnsureSuccessStatusCode(); 我试过UrlEncoding电子邮件地址没有运气。 任何建议表示赞赏。

无法在ASP.NET WebApi控制器中读取Request.Content

我在TransferMode.Streamed HttpSelfHostConfiguration exe中使用WebApi编写代理。 当我使用fiddler发布到我的ApiController时,出于某种原因我无法读取Request.Content – 即使我有POSTed数据它也返回“” public class ApiProxyController : ApiController { public Task Post(string path) { return Request.Content.ReadAsStringAsync().ContinueWith(s => { var content = new StringContent(s.Result); //s.Result is “” CopyHeaders(Request.Content.Headers, content.Headers); return Proxy(path, content); }).Unwrap(); } private Task Proxy(string path, HttpContent content) { … } } 这是我的网络请求 POST http://localhost:3001/api/values HTTP/1.1 Host: localhost:3001 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Content-Type: […]

Swashbuckle 5找不到我的ApiControllers

我真的需要我的WebAPI 2项目的API文档,我使用了Swashbuckle 5 NuGet包。 开箱即用,我可以点击{myrooturl} / swagger并弹出一个UI,但那里没有控制器,方法或任何东西。 只是我的标题:[base url:/EM.Services,api version:v1] 我看了一下Swashbuckle文档,因为我正在使用由IIS托管的OWIN,所以我修改了SwaggerConfig: c.RootUrl(req => req.RequestUri.GetLeftPart(UriPartial.Authority) + req.GetRequestContext().VirtualPathRoot.TrimEnd(‘/’)); 按照这个文件: https : //github.com/domaindrivendev/Swashbuckle/blob/1326e753ce9b3a823b3c156b0b601134692ffc58/README.md#transitioning-to-swashbuckle-50 我还设置了项目的构建以生成XML文档,并将我的SwaggerConfig指向它: private static string GetXmlCommentsPath() { // tried with an without the \bin return String.Format(@”{0}\bin\EM.Services.XML”, AppDomain.CurrentDomain.BaseDirectory); } 我不确定XML文档的工作/不工作是否与它有关,因为我在swagger-ui页面上完全没有控制器。 值得一提的是,我的所有控制器都inheritance自BaseController,而BaseController又inheritance自ApiController。 我的WebApiConfig有什么东西搞砸了吗? public static void Register(HttpConfiguration config) { config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); config.Filters.Add(new ValidateModelAttribute()); config.Filters.Add(new BaseAuthenticationAttribute()); config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( […]