Web Api发布错误 - >值不能为空。参数名称:uriString

问题描述 投票:3回答:2

我对Web Api比较新,我在POST一个Person对象时遇到了麻烦。如果我在调试中运行,我看到我的uriString永远不会被设置,我不明白为什么。因此,我在Fiddler中为所有尝试的帖子收到“400 Bad Request”错误。

我试图复制其他人在Post动作中所做的事情。我发现的每个示例都使用存储库将人员添加到数据库中。但是我没有存储库,而是使用NHibernate Save方法来执行此功能。以下是域类,按代码文件映射,WebApiConfig和PersonController。

public class Person
{
    public Person() { }

    [Required]
    public virtual string Initials { get; set; }
    public virtual string FirstName { get; set; }
    public virtual char MiddleInitial { get; set; }
    public virtual string LastName { get; set; }
}

public class PersonMap : ClassMapping<Person>
{
    public PersonMap() 
    {
        Table("PERSON");
        Lazy(false);

        Id(x => x.Initials, map => map.Column("INITIALS"));

        Property(x => x.FirstName, map => map.Column("FIRST_NAME"));
        Property(x => x.MiddleInitial, map => map.Column("MID_INITIAL"));
        Property(x => x.LastName, map => map.Column("LAST_NAME"));  
    }
}



public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
        config.Formatters.Remove(config.Formatters.XmlFormatter);

        config.Services.Replace(typeof(IHttpActionSelector), new HybridActionSelector());



        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}/{action}/{actionid}/{subaction}/{subactionid}",
            defaults: new { id = RouteParameter.Optional, action = RouteParameter.Optional,
                            actionid = RouteParameter.Optional, subaction = RouteParameter.Optional, subactionid = RouteParameter.Optional }
        );


        config.BindParameter( typeof( IPrincipal ), new ApiPrincipalModelBinder() );

        // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
        // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
        // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
        //config.EnableQuerySupport();

        // To disable tracing in your application, please comment out or remove the following line of code
        // For more information, refer to: http://www.asp.net/web-api
        config.EnableSystemDiagnosticsTracing();
    }
}



public class PersonsController : ApiController
{
    private readonly ISessionFactory _sessionFactory;

    public PersonsController (ISessionFactory sessionFactory)
    {
        _sessionFactory = sessionFactory;
    }

    // POST api/persons
    [HttpPost]
    public HttpResponseMessage Post(Person person)
    {
        var session = _sessionFactory.GetCurrentSession();

        using (var tx = session.BeginTransaction())
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
                }

                var result = session.Save(person);
                var response = Request.CreateResponse<Person>(HttpStatusCode.Created, person);

                string uriString = Url.Route("DefaultApi", new { id = person.Initials });
                response.Headers.Location = new Uri(uriString); 


                tx.Commit();
                return response;
            }
            catch (Exception)
            {
                tx.Rollback();
            }
            throw new HttpResponseException(HttpStatusCode.BadRequest);
        }
    }
}

提琴信息:POST // localhost:60826 / api / employees HTTP / 1.1

请求标头:用户代理:Fiddler内容类型:application / json主机:localhost:xxxxx内容长度:71

请求机构:

{“缩写”:“MMJ”,“姓氏”:“乔丹”,“名字”:“迈克尔”}

该行永远不会将uriString设置为正确的值。 string uriString = Url.Route(“DefaultApi”,new {id = person.Initials});我也尝试过使用Url.Link而不是Url.Route。我尝试在'new'块中添加controller =“Persons”,但这没有效果。为什么不设置uriString?我会听到任何想法。

编辑我试过

string uriString = Url.Link("DefaultApi", new { controller = "Persons", id = person.Initials, action="", actionid="", subaction="", subactionid="" });

以及使用单独的routeconfig

config.Routes.MapHttpRoute(
            name: "PostApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional
        } );

string uriString = Url.Link("PostApi", new { controller = "Persons", id = person.Initials});

并没有运气。

通过使用下面的代码行,我能够使这个帖子工作。我不完全确定这是否是正确的方法,所以如果有人知道不同,请分享。否则,我会很乐意使用这种方法。

response.Headers.Location = new Uri(this.Request.RequestUri.AbsoluteUri + "/" + person.Initials);
nhibernate post asp.net-web-api asp.net-web-api-routing mapping-by-code
2个回答
0
投票

问题似乎在这里:

string uriString = Url.Route("DefaultApi", new { id = person.Initials });

您只需要传递id,而您需要传递其他参数,如控制器等。


0
投票

您可以这样构造URL:

string uriString = Url.Action("ActionName", "ControllerName", new { Id = person.Initials });
© www.soinside.com 2019 - 2024. All rights reserved.