我有以下字段的模型:
-Id : Required (database generated)
-Title : Required
-Status : Required
-Comments
Run Code Online (Sandbox Code Playgroud)
当我运行一个帖子给出这个:
{
"title":"WOHOO",
"status":"STATUS"
}
Run Code Online (Sandbox Code Playgroud)
一切都运行良好.但是,当我使用以下内容运行帖子时:
{
"title":"WOHOO"
}
Run Code Online (Sandbox Code Playgroud)
我得到模型状态问题因为状态是必需的.但是,在我的post方法中它是这样的:
[Route(""), ResponseType(typeof(MyModel))]
public IHttpActionResult PostMyModel(MyModel model)
{
// Save request in DB
model.status = "Waiting";
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.MyModels.Add(model);
try
{
db.SaveChanges();
}
catch (DbUpdateException)
{
if (ModelExists(model.id))
{
return Conflict();
}
else
{
throw;
}
}
return CreatedAtRoute("DisplayMyModel", new { id = model.id }, model);
}
Run Code Online (Sandbox Code Playgroud)
我在此方法的开头设置状态,但ModelState在请求开始时是原样的.我可以清除ModelState ModelState.Clear(),但是如何重新验证新模型?
这是在ApiController中.
我正在使用.NET Framework 4.5.1和C#开发ASP.NET Web Api 2.2应用程序.
我有一个这种方法的控制器:
public HttpResponseMessage Get(
string productCode,
byte codeLevel,
string productionOrderName,
string batchName,
string lineName,
int quantity)
{
Run Code Online (Sandbox Code Playgroud)
这就是我如何配置其路线WebApiConfig:
config.Routes.MapHttpRoute(
name: "ExternalCodesActionApi",
routeTemplate: "api/ExternalCodes/{action}/{productCode}/{codeLevel}/{productionOrderName}/{batchName}/{lineName}/{quantity}",
defaults: new { controller = "ExternalCodes" });
Run Code Online (Sandbox Code Playgroud)
但是现在我在同一个控制器(ExternalCodesController)上有另一种方法:
[HttpPut]
public HttpResponseMessage SetCodesAsUsed(List<string> codes)
{
Run Code Online (Sandbox Code Playgroud)
但是,使用该路由,当我使用该方法(http:// myHost:53827/api/ExternalCodes/SetCodesAsUsed)时,我得到一条InvalidOperationException消息:
"找到了与请求匹配的几个操作:
SetProCodesAsUsed类型MyProject.Web.API.Controllers.ExternalCodesController中的
SetCodesAsUnUsed类型MyProject.Web.API.Controllers.ExternalCodesController",
还有另一种方法ExternalCodesController:
[HttpPut]
public HttpResponseMessage SetCodesAsUnUsed(List<string> codes)
{
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
这些方法有不同的名称.
Webapi响应状态码401时,如何禁用“需要身份验证”弹出窗口?

那是我的webapi配置
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(Startup.OAuthOptions.AuthenticationType));
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
//config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Run Code Online (Sandbox Code Playgroud) asp.net authentication asp.net-mvc asp.net-web-api asp.net-web-api2
是否可以定义可选参数,或者将空值作为参数传递到Web API中的OData v4函数中?
鉴于此函数定义:
ODataConventionModelBuilder builder
var config = builder.EntityType<model.MyType>()
.Collection
.Function("Myfunction")
.ReturnsCollectionFromEntitySet<model.MyType>("MyType");
config.Parameter<int>("Id");
config.Parameter<string>("SomeString");
Run Code Online (Sandbox Code Playgroud)
和这个控制器动作:
[HttpGet]
public System.Web.OData.PageResult<model.MyType> MyFunction(int id, string someString)
{
return ...;
}
Run Code Online (Sandbox Code Playgroud)
我试过用这些方法调用这个函数:
odata/MyType/Namespace.MyFunction(Id=123,SomeString='lalal')工作正常
odata/MyType/Namespace.MyFunction(Id=123)给我一个404
odata/MyType/Namespace.MyFunction(Id=123,SomeString='')给我一个400错误'一个值是必需的,但在请求中不存在.
odata/MyType/Namespace.MyFunction(Id=123,SomeString=null)成功,但将字符串值'Microsoft.OData.Core.ODataNullValue'发送到控制器操作中的SomeString-paramater.我希望得到一个常规的空值.
测试版本:
升级到Microsoft.AspNet.OData v5.5.0-beta证明可以解决这个问题(部分).
进一步挖掘证明了ModelState对象无效.modelstate对象抱怨第三个(?)参数中存在错误,其中键为'someString.String'.错误是"值是必需的,但请求中不存在."
Fan Ouyang在https://github.com/VikingsFan/SampleForOData/tree/master/ODataFunctionSample提供的代码示例中可以轻松地重现该问题.只需运行示例并检查'CustomersController'中的ModelState继承的ModelState属性.
这似乎是asp.net web api中的一个错误.我更改了我的ModelState逻辑,忽略了包含'.'的任何模型状态键,但这只是潜在问题的解决方法.
我已经将ASP.NET web API self hostNuGet包管理器添加到我的项目(一个Windows服务项目)中,Nuget添加了这些库
当我尝试添加Route属性时,我无法在System.Web.Http中找到它.当我在MSDN中寻找这个类时,我看到它在这个包下
我需要安装另一个包还是添加另一个包?
在这里,我使用DI框架(Ninject),它工作正常.但是面临的问题之一是,我有一个带有单个构造函数的基类,它接受一个接口的实现.
public class BaseApiController : ApiController
{
readonly IAccessService _accessService;
public BaseApiController(IAccessService accessService)
{
this._accessService = accessService;
}
}
Run Code Online (Sandbox Code Playgroud)
当我从这个基类继承到所有其他控制器时,这些控制器具有实现自己接口的构造函数.我得到错误'BaseApiController'不包含一个带0参数的构造函数,好吧,我明白了.派生类是
public class DiscoverController : BaseApiController
{
readonly IDiscoverService _discoverService;
readonly IAccessService _accessService;
public DiscoverController(IDiscoverService discoverService,IAccessService accessService)
{
_accessService = accessService;
_discoverService = discoverService;
}
}
Run Code Online (Sandbox Code Playgroud)
我怎么能这样做而不修改派生类ctor采取类似的参数并将该值传递给基本ctor,如果你建议更好的方法处理这个,我将不胜感激?
c# model-view-controller dependency-injection ninject asp.net-web-api
我在这个问题上读了很多.我读到我可以在web api asp.net上使用在Umbraco中创建休息服务.
我可以在Umbraco后台创建这个api吗?如果没有,我如何将服务连接到我当地的Umbraco网站?
我找不到一个显示这个的简单教程.
编辑:
我想在客户端获取Umbraco内容数据.我读到我可以在服务器端(Umbraco)休息服务中创建,当我调用我的Umbraco服务器的特定URL时,我可以获取数据.
当我尝试不带可选参数的WebAPI控制器时遇到了404错误。我尝试将Global.asax.cs中的路线初始化命令重新排序无济于事。WebAPI在一个区域中,因此我注释掉该区域的路由信息,因此找不到该路由。这是我所拥有的:
在WebApiConfig.cs中:
public static void Register(HttpConfiguration configuration)
{
configuration.Routes.MapHttpRoute("DefaultAPI",
"API/{controller}/{action}/{id}",
new { id = RouteParameter.Optional });
// From http://weblogs.asp.net/fbouma/how-to-make-asp-net-webapi-serialize-your-llblgen-pro-entities-to-json
var json = configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
json.SerializerSettings.ContractResolver = new DefaultContractResolver()
{
IgnoreSerializableInterface = true,
IgnoreSerializableAttribute = true
};
var appXmlType = configuration.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
configuration.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
}
Run Code Online (Sandbox Code Playgroud)
在APIAreaRegistration.cs中:
public override void RegisterArea(AreaRegistrationContext context)
{
//context.MapRoute(
// "API_default",
// "API/{controller}/{action}/{id}",
// new { action = "Index", id = UrlParameter.Optional }
//);
}
Run Code Online (Sandbox Code Playgroud)
在Global.asax.cs中:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
//WebApiConfig.Register(GlobalConfiguration.Configuration); …Run Code Online (Sandbox Code Playgroud) 这可能是一个愚蠢的问题,我.svc对ODATA服务的后缀只有一点混淆,因为我看到的大多数示例.svc在根URL上总是有后缀,例如:
http://services.odata.org/V4/Northwind/Northwind.svc/
甚至在ODATA文档示例上:

在ASP.NET Web Api上构建ODATA时,我发现后缀.svc实际上并不是强制性的,如果我们想要路由配置,我们可以添加它.
那么.svc为了构建ODATA服务,为根URL 添加后缀的目的是什么呢?或者只是指定这是ODATA 服务的约定?
我正在关注我的Web API和AngularJS项目的Onion架构.在Infrastructure.DependencyResolution部分中,我使用的是Simple Injector.这是我的代码:
[assembly: PreApplicationStartMethod(typeof(IocConfig), "RegisterDependencies")]
namespace Infrastructure.DependencyResolution
{
public class IocConfig
{
private static Container _container;
public static void RegisterDependencies()
{
_container = new Container();
_container.Verify();
_container.RegisterWebApiRequest<IEntitiesContext>(() =>
{
return new MyContext();
});
_container.RegisterWebApiRequest<IUserRepository, UserRepository>();
_container.RegisterWebApiRequest<IAccountService, AccountService>();
_container.RegisterWebApiRequest<IUnitOfWork, UnitOfWork>();
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我尝试将url转到我的帐户控制器,我收到此错误:
尝试创建"AccountController"类型的控制器时发生错误.确保控制器具有无参数的公共构造函数.
我搜索并发现Simple Injector有一些不同的Web Api代码,如他们的网站所建议的那样:
// This is an extension method from the integration package.
container.RegisterWebApiControllers(GlobalConfiguration.Configuration);
Run Code Online (Sandbox Code Playgroud)
我也复制了它,但它不接受GlobalConfiguration.Configuration,我想是因为我在库项目中使用它.
当我在RegisterDependencies方法中设置断点时,Visual Studio不会在断点处停止.
有人能告诉我去哪儿的路吗?
.net onion-architecture simple-injector asp.net-web-api asp.net-identity
asp.net-web-api ×10
c# ×4
.net ×2
asp.net ×2
asp.net-mvc ×2
odata ×2
model ×1
modelstate ×1
ninject ×1
odata-v4 ×1
umbraco ×1
umbraco7 ×1
validation ×1