Tag: asp.net web api2

使用URL在Web Api 2中进行控制器版本控制

我想为我的控制器使用基于URL的版本控制。 我发现的最佳解决方案是下面的代码。 我正在寻找更好的解决方案。 我试过Constrain它不起作用也许我做了一些错误我唯一关心的是在不同的命名空间中使用同名的控制器……?! 我用字符串合并到创建想要的类型。 可能这不是一个好主意。 如果你知道的话,请为这个主题发送好的参考资料…..? public class ControllerVersioning : DefaultHttpControllerSelector { private HttpConfiguration _config; public ControllerVersioning(HttpConfiguration config) : base(config) { _config = config; } public override HttpControllerDescriptor SelectController(HttpRequestMessage request) { var routeData = request.GetRouteData(); var controllerName = routeData.Values[“controller”].ToString(); controllerName = char.ToUpper(controllerName[0]) + controllerName.Substring(1); var versionName = routeData.Values[“version”].ToString(); HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(); controllerDescriptor.Configuration […]

Web Api 2路由问题,URL中包含特殊字符

在开发Web Api 2 REST服务的过程中,我们发现了一个路由问题。 端点如下: …/{电子邮件}/… 问题是电子邮件可能包含特殊字符,例如“+”,这会导致找不到404资源。 我们真的希望该服务的用户能够在URL中指定电子邮件。 但由于电子邮件在法律上也可以包含“&”,因此不能将其移动到URL参数。 我们将如何解决这个问题? 关心弗雷德里克

使用Moq进行Web Api 2控制器测试,在Mocked DbContext中加载相关实体

我正在尝试对使用Entity Framework 6的一些Web Api 2控制器进行unit testing,但是在添加实体后加载相关实体时遇到问题。 我正在使用Moq创建一个模拟的DbContext和DbSet,并添加了 public virtual void MarkAsModified(T item) where T : class { Entry(item).State = EntityState.Modified; } 绕过_db.Entry(foo).State = EntityState.Modified; 关于Put动作的问题。 在这个简化的例子中,Api Action是一个post,我们需要找回2个相关实体(Bar和Qux)。 [ResponseType(typeof (Foo))] public async Task PostFoo(Foo foo) { if (!ModelState.IsValid) { return BadRequest(ModelState); } //Do other stuff _db.Foos.Add(foo); _db.Entry(foo).Reference(x => x.Bar).Load(); _db.Entry(foo).Reference(x => x.Qux).Load(); await _db.SaveChangesAsync(); return CreatedAtRoute(“DefaultApi”, […]

为什么在控制器上下文之外获取路由值如此困难?

我不明白这背后的交易是什么,为什么在控制器的Request中获取路由值如此容易,但几乎不可能在HttpContext.Current.Request上做同样的事情? 也许我只是不知道更好的方式而且存在。 有人可以确认这是获取控制器外部路径数据的唯一方法吗? 例 [Route(“{id}”), HttpGet] public IHttpActionResult Test() { // Simple and easy var route1 = Request.GetRouteData().Values[“id”]; // Wat. This is also ~6 times slower var routeValues = (IHttpRouteData[]) HttpContext.Current.Request.RequestContext.RouteData.Values[“MS_SubRoutes”]; var route2 = routeValues.SelectMany(x => x.Values).Where(x => x.Key == “id”).Select(x => x.Value).FirstOrDefault(); return Ok(route1 == route2); // true }

使用Web API 2进行Autofac – 无参数构造函数错误

我想在我的Web API 2项目上设置Autofac。 我以前只用了几次。 我使用Nuget安装了Autofac和Autofac.WebApi2 。 然后在我的Startup课程中我做了这个: public partial class Startup { public void Configuration(IAppBuilder app) { // Get our http configuration var config = new HttpConfiguration(); // Register the Autofac middleware FIRST. This also adds // Autofac-injected middleware registered with the container. var container = ConfigureInversionOfControl(app, config); // Register all areas AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); // […]

WebApi2 IHttpActionResult强类型返回值

这样做是可能的,也不是理想的:(一个非常简单的例子!) [Serializable] public class MyRecord { public string key {get; set;} public string data {get; set;} } public async Task Get(string SomeKey) { if(ExistsInDB(SomeKey)) { return Ok(SomeRecordFromDB(SomeKey)); //SomeRecord() returns a POCO MyRecord. } else { //I know I can return NotFound() but not the focus of my Q return Ok(false); //returns “False” } } 有效地certificate在返回类型上没有编译时错误检查。 […]

Web Api 2 – 自定义数据类型JSON序列化

我实际上是Web Api的新手,所以我的问题可能听起来有些奇怪。 我有简单的API来返回有关价格变化的历史信息。 我的控制器的动作如下所示: [HttpGet] [Route(“api/history/{id}/{size}”)] public async Task<IEnumerable> GetHistory(string id, Size size) 其中PriceHistoryRecordModel是 [DataContract] public class PriceHistoryRecordModel { [DataMember] public DateTime Date { get; set; } [DataMember] public double Value { get; set; } } 但是,问题是 – action以下列格式返回JSON [{“Date”:”2016-02-07T08:22:46.212Z”,”Value”:17.48},{“Date”:”2016-02-08T09:34:01.212Z”,”Value”:18.37}] 但是,由于客户对数据格式的特定要求,我需要我的JSON这样看 [[1238371200000,17.48],[1238457600000,18.37]] 所以,我想知道 如果有办法实现这样的自定义序列化? 我可以将此自定义序列化包装在属性中并将其用作方面吗?

web api路由和httppost

我正在使用WEB API 2构建API。 我有以下API控制器: [RoutePrefix(“api/account”)] public class AccountController : ApiController { [Route(“login”)] [HttpPost] public IHttpActionResult AuthenticateUser(string username, string password) { if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) { return BadRequest(“You must submit username and password”); } if (!Membership.ValidateUser(username, password)) { return BadRequest(“Incorrect username or password”); } FormsAuthentication.SetAuthCookie(username, true); return Ok(); } } 和jquery函数: $(document).ready(function () { $(“#login-form”).submit(function (e) […]

多个可选的查询字符串参数REST API GET

我正在使用web api 2来实现一个宁静的服务。 在对最佳实践进行一些研究之后,每个人似乎都对如何做以下事情有不同的看法。 我有一个GET public HttpResponseMessage Get(string crewId, string shiftDate, int offset = 1, int limit = 10) 此GET方法返回一个列表。 有多种方法可以从此方法获取数据。 仅限crewId 仅限shiftDate 要么 通过crewId和shiftDate获取 你(1)将crewId和shiftDate标记为可选吗? public HttpResponseMessage Get(string crewId = null, string shiftDate = null, int offset = 1, int limit = 10) 然后有一堆if语句来检查填充的内容和未填充的内容以便能够执行操作 if(crewId != null && shiftDate == null){ // Get by […]

将.net core 2的JWT Authentication实现转移到asp.net web api 2

我在.net core 2应用程序中实现了JWT身份validation ,它工作正常。 我想在asp.net web api 2应用程序中使用此实现和结构但我收到错误 我的结构: JwtTokenBuilder类: using System; using System.Collections.Generic; using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Linq; namespace solution.Authentication { public sealed class JwtTokenBuilder { private SecurityKey securityKey = null; private string subject = “”; private string issuer = “”; private string audience = “”; private Dictionary claims = new […]