开发者

C# MVC NerdDinner authorization helper method problem

I'm currently going through the ASP.NET MVC NerdDinner tutorial and am having a problem with a particular helper method related to user authorization. The idea is that only users who "own" a particular dinner should be able to edit or delete it (based on the Dinner object's HostedBy property).

I have the following method in my Dinner object:

public partial class Dinner {

    public bool IsHostedBy(string userName) {
        return HostedBy.Equals(userName, StringComparison.InvariantCultureIgnoreCase);
    }

    // other stuff removed for brevity

}

and in my View I'm trying to show/hide links based on whether the logged in user is the dinner's host:

<% if (Model.IsHostedBy(Context.User.Identity.Name)) { %>

    <%= Html.ActionLink("Edit Dinner", "Edit", ne开发者_如何学Gow { id = Model.DinnerID })%>
    |
    <%= Html.ActionLink("Delete Dinner", "Delete", new { id = Model.DinnerID })%>    

<% } %>

The problem is that IsHostedBy() never returns true. I've written User.Identity.Name and Dinner.HostedBy to the screen to verify they're the same, but the method still returns false. I'm uncertain how to track down the problem.

I'm new to both C# and ASP.NET MVC, so it's very likely I'm missing something easy. Any help is appreciated and I'd be happy to post more information if it's needed.


While I'm at it I may as well write the Answer.

Check for errent spaces in the two strings.


I'm guessing that HostedBy and userName aren't actually the same string!

Some debugging ideas:

1st) Try forcing it to always return true:

public bool IsHostedBy(string userName) {
    return true;
}

If this lets you return true back into the view, at least you can know that the code you're writing in the IsHostedBy method is being executed.

2nd) Add a console-out to see for yourself if the two strings are indeed equal:

   public bool IsHostedBy(string userName) {
        Console.WriteLine("userName: {0} / HostedBy: {1}", userName, HostedBy);  
        return true;
    }

This will help you inspect the values of these items. Or you could just set a breakpoint at the return statement and see what they are as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜